/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014 @ ShenZhen ,China
*******************************************************************************/
#include "Directory.h"
#include <limits.h>
#include <stdlib.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <algorithm>

Directory::Directory():
m_currentPath(".")
{
}

Directory::~Directory()
{
}

bool Directory::enter(const string & path)
{
    string resolved;
    if (path.empty())
    {
        return false;
    }
    if (path[0]!='/')
    {
        resolved = m_currentPath+"/"+path;
    }
    else
    {
        resolved = path;
    }
    DIR* dirp;
    struct dirent * dp = NULL;
    dirp = opendir(resolved.c_str());
    if (NULL == dirp)
    {
        return false;
    }
    closedir(dirp);
    char buf[1024]={0};
    if (NULL==realpath(resolved.c_str(),buf))
    {
        return false;
    }
    m_currentPath = string(buf);
    return true;
}

string Directory::current()
{
    return m_currentPath;
}

vector<string> Directory::listAll()
{
    vector<string> fileVector;
    std::string fileName;
    DIR* dirp = opendir(m_currentPath.c_str());
    if (NULL == dirp)
    {
        return fileVector;
    }
    #if 0
    struct dirent *dp1 = (struct dirent*)malloc(sizeof(struct dirent));
    struct dirent *dp2 = (struct dirent*)malloc(sizeof(struct dirent));
    while ((readdir_r(dirp,dp1,&dp2))!=0)
    {
        fileName = string(dp2->d_name);
        fileVector.push_back(fileName);
    }
    closedir(dirp);
    free(dp1);
    free(dp2);
    #else
    struct dirent *dp;
    while ((dp=readdir(dirp))!=NULL)
    {
        fileName = string(dp->d_name);
        fileVector.push_back(fileName);
    }
    closedir(dirp);
    #endif
    sort(fileVector.begin(),fileVector.end());
    return fileVector;
}

